package com.example.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.example.echo.EchoServerHandler;

import java.net.InetSocketAddress;

/**
 * 请描述当前类的作用
 *
 * @author LSQ
 * @since 2023/2/26 14:41
 */
public class NettyServer {

    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        EchoServerHandler echoServerHandler = new EchoServerHandler();

        // 创建EventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            // 创建ServerBootstrap
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(group)
                    // 指定所使用的NIO传输Channel
                    .channel(NioServerSocketChannel.class)
                    // 使用指定的端口设置套接字地址
                    .localAddress(new InetSocketAddress(port))
                    // 添加一个EchoServerHandler到子Channel的ChannelPipeline
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(echoServerHandler);
                        }
                    });

            // 异步绑定服务器 调用sync()方法阻塞至绑定完成
            ChannelFuture channelFuture = serverBootstrap.bind().sync();
            // 获取Channel的ChannelFuture 并且阻塞当前线程直到其完成
            channelFuture.channel().closeFuture().sync();
        } finally {
            // 优雅的关闭
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        NettyServer nettyServer = new NettyServer(6666);
        nettyServer.start();
    }

}
